class Solution {
public:
    int countGoodNodes(vector<vector<int>>& edges) {
        int n = edges.size() + 1;
        // 建树
        vector<vector<int>> g(n);
        for(auto e:edges){
            g[e[0]].push_back(e[1]);
            g[e[1]].push_back(e[0]);
        }
        int ans = 0;
        function<int(int,int)>dfs = [&](int x,int fa)->int{
            bool flag = true;
            int pre = -1;
            int res = 1;
            for(int y:g[x]){
                if(y != fa){
                    int sz = dfs(y, x);
                    res += sz;
                    if(pre == -1) pre = sz;
                    else if(flag) flag &= (pre == sz);
                }
            }
            ans += flag;
            return res;
        };
        dfs(0, -1);
        return ans;
    }
};